<template>
  <el-row>
    <h2 align="center">用户管理</h2>
    <el-row>
      <el-col :span="2"><p></p></el-col>
      <el-col :span="22">
        <el-form
          :inline="true"
          :model="searchForm"
          size="mini"
          class="demo-form-inline"
        >
          <el-form-item label="关键字">
            <el-input
              clearable
              v-model="searchForm.keyword"
              placeholder="请输入关键字"
            ></el-input>
          </el-form-item>
          <el-form-item>
            <el-button
              type="primary"
              icon="el-icon-search"
              @click="handleSubmitSearchForm"
              >查询</el-button
            >
          </el-form-item>
          <el-form-item>
            <el-button
              v-if="!cacheName"
              type="success"
              icon="el-icon-plus"
              @click="handleSaveOrEdit"
              >新增</el-button
            >
          </el-form-item>
        </el-form>
      </el-col>
    </el-row>
    <el-row>
      <el-col :span="2"><p></p></el-col>
      <el-col :span="22">
        <el-table :data="tableData" style="width: 100%">
          <el-table-column label="ID" prop="id" />
          <el-table-column label="用户名" prop="username" />
          <el-table-column label="年龄" prop="age" />
          <el-table-column label="性别" prop="sex">
            <template v-slot="scope">
              {{
                scope.row.sex == 0 ? "男" : scope.row.sex == 1 ? "女" : "保密"
              }}</template
            >
          </el-table-column>
          <el-table-column label="管理员" prop="admin">
            <template v-slot="scope">
              {{ scope.row.admin == 0 ? "否" : "是" }}</template
            >
          </el-table-column>
          <el-table-column label="邮箱" prop="email" />
          <el-table-column label="图片" prop="image">
            <template v-slot="scope">
              <el-tooltip
                class="tooltipItem"
                effect="dark"
                content="点击更换头像 "
                placement="bottom"
              >
                <img
                  @click="handleChangeAvatar(scope.row)"
                  width="80"
                  :src="scope.row.image"
                  alt=""
                />
              </el-tooltip>
            </template>
          </el-table-column>
          <el-table-column label="录入时间" prop="date" />
          <el-table-column label="操作" width="200" fixed="right">
            <template slot-scope="scope">
              <el-button size="mini" @click="handleSaveOrEdit(scope.row)"
                >编辑</el-button
              >
              <el-button
                size="mini"
                type="danger"
                @click="handleDelete(scope.$index, scope.row)"
                >删除</el-button
              >
            </template>
          </el-table-column>
        </el-table>
      </el-col>
    </el-row>
    <el-row>
      <el-pagination
        align="right"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="searchForm.currentPage"
        :page-sizes="[5, 10, 20, 50]"
        :page-size="100"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
      >
      </el-pagination>
    </el-row>
    <el-dialog
      :title="dialogTitle"
      width="50%"
      :visible.sync="dialogFormVisible"
    >
      <el-form :model="editForm">
        <el-form-item label="用户名" label-width="60px">
          <el-input v-model="editForm.username" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item label="密码" label-width="60px">
          <el-input v-model="editForm.password" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item label="年龄" label-width="60px">
          <el-input v-model="editForm.age" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item label="性别" label-width="60px">
          <el-radio-group v-model="editForm.sex">
            <el-radio :label="0">男</el-radio>
            <el-radio :label="1">女</el-radio>
            <el-radio :label="2">保密</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="管理员" label-width="60px">
          <el-switch
            :disabled="adminDisabled"
            v-model="editForm.admin"
            active-color="#13ce66"
            inactive-color="#ff4949"
          >
          </el-switch>
        </el-form-item>
        <el-form-item label="邮箱" label-width="60px">
          <el-input v-model="editForm.email" autocomplete="off"></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogFormVisible = false">取 消</el-button>
        <el-button type="primary" @click="handleSubmit">确 定</el-button>
      </div>
    </el-dialog>
  </el-row>
</template>

<script>
import axios from "axios";
export default {
  name: "User",
  data() {
    return {
      adminDisabled: false,
      dialogFormVisible: false,
      tableData: [],
      randomUrl: null,
      cacheName: false,
      tempUsername: "",
      // 缓存用户
      cache_user: {},
      editForm: {
        sex: 0,
      },
      dialogTitle: "用户新增",
      searchForm: {
        currentPage: 1,
        pageSize: 5,
        keyword: "",
      },
      total: 0,
    };
  },
  methods: {
    watchUsername(username) {
      return this.tempUsername === username;
    },
    randomAvatar() {
      const config = {
        method: "get",
        url: "https://api.btstu.cn/sjtx/api.php",
        params: {
          lx: "b1",
          format: "json",
        },
        responseType: "json",
      };
      axios(config)
        .then((res) => {
          this.randomUrl = res.data.imgurl;
        })
        .catch((err) => {
          this.$message.error(err.message);
        });
    },
    async fetchData() {
      const { data } = await axios({
        url: "/user/list",
        method: "get",
        params: this.searchForm,
      });
      this.total = data.data.total;
      this.tableData = data.data.list;
      this.searchForm.current = data.data.currentPage;
      this.searchForm.pageSize = data.data.pageSize;
    },
    handleSaveOrEdit(row) {
      if (row.admin) {
        this.adminDisabled = false
      }else {
        this.adminDisabled = true
      }
        this.editForm = {};
        this.dialogFormVisible = true;
        this.editForm = { ...row };
        this.tempUsername = row.username;
        this.dialogTitle = row.id ? "用户编辑" : "用户新增";
        this.editForm.sex = row.id ? row.sex : 0;
        if (!row.id) {
          this.randomAvatar();
        }
    },
    handleSubmit() {
      this.dialogFormVisible = false;
      if (!this.editForm.id) {
        this.editForm.image = this.randomUrl;
      }
      axios({
        url: "/user/saveOrUpdate",
        method: "post",
        data: this.editForm,
      }).then((res) => {
        this.$message.success("操作成功！");
        if (this.watchUsername(this.editForm.username)) {
          this.fetchData();
        } else {
          if(this.cache_user.admin) {
            this.$message.success("修改成功");
          } else {
            this.$message.success("用户名发生改变,请重新登录");
            this.$router.push("/");
          }
        }
      });
    },
    handleChangeAvatar(row) {
      this.randomAvatar();
      this.$confirm("此操作将更换当前头像, 是否继续?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(() => {
          this.editForm = { ...row };
          // 调用接口生成随机图片
          this.editForm.image = this.randomUrl;
          axios({
            url: "/user/saveOrUpdate",
            method: "post",
            data: this.editForm,
          }).then((res) => {
            this.$message({
              type: "success",
              message: "头像更换成功!",
            });
            this.fetchData();
          });
        })
        .catch(() => {
          this.$message({
            type: "info",
            message: "已取消更换",
          });
        });
    },
    handleDelete(index, row) {
      if (this.cacheName) {
        this.$message.warning("没有权限操作");
      } else {
        this.$confirm("此操作将永久删除该文件, 是否继续?", "提示", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning",
        })
          .then(() => {
            axios({
              url: `/user/delete/${row.id}`,
              method: "get",
            }).then((res) => {
              this.$message.success("删除成功!");
              this.fetchData();
            });
          })
          .catch(() => {
            this.$message({
              type: "info",
              message: "已取消删除",
            });
          });
      }
    },
    handleSizeChange(pageSize) {
      this.searchForm.pageSize = pageSize;
      this.fetchData();
    },
    handleCurrentChange(current) {
      this.searchForm.current = current;
      this.fetchData();
    },
    handleSubmitSearchForm() {
      this.fetchData();
    },
    async firstSearchData() {
      this.cache_user = JSON.parse(localStorage.getItem("user"));
      this.searchForm.initKeyword = this.cache_user.username;
      const { data } = await axios({
        url: "/user/list",
        method: "get",
        params: this.searchForm,
      });
      this.total = data.data.total;
      this.tableData = data.data.list;
      this.searchForm.current = data.data.currentPage;
      this.searchForm.pageSize = data.data.pageSize;
      const temp = Object.assign([], data.data.list);
      if (temp.length == 1) {
        this.cacheName = true;
      }
    },
  },
  created() {
    this.firstSearchData();
    // localStorage.clear();
  },
};
</script>

<style scope>
img:hover {
  cursor: pointer;
}
</style>
